<template>
  <div>
    <el-button type="primary" size="default" @click="handleRole(null)"
      >新增角色</el-button
    >

    <el-table :data="tableData" style="width: 100%" row-key="objectId">
      <el-table-column label="角色名称" width="180" prop="roleName">
      </el-table-column>
      <el-table-column label="角色权限">
        <template #default="scope">
          <el-tag v-for="item in scope.row.permission">
            {{ routesMap[item] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleRole(scope.row, scope.$index)"
            >编辑</el-button
          >
          <el-popconfirm
            title="删除后无法找回，确定不是手抖了?"
            confirm-button-text="确定"
            cancel-button-text="取消"
            @confirm="handleDelete(scope.$index, scope.row)"
          >
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer
      :title="rowData ? '修改角色' : '新增角色'"
      v-model="drawer"
      direction="rtl"
      size="30%"
    >
      <RoleForm :role-data="rowData" @update-list="handleUpdate" />
    </el-drawer>
  </div>
</template>

<script>
import { roleGet, roleDel } from "@/api/user.js";
import RoleForm from "./components/role-form.vue";
import { routesToMap } from "@/utils/tools.js";
export default {
  components: {
    RoleForm,
  },
  data() {
    return {
      tableData: [],
      drawer: false,
      routesMap: null,
      rowData: null,
    };
  },
  created() {
    roleGet().then((res) => {
      this.tableData = res.data.results;
      console.log("组件内数据", res);
    });
    // console.log(routesToMap());
    this.routesMap = routesToMap();
  },
  methods: {
    handleRole(row, index) {
      console.log(row, index);
      this.drawer = true;
      this.rowData = row; //可能为null、对象
    },
    handleDelete(index, row) {
      console.log(index, row);
      roleDel(row.objectId).then((res) => {
        this.tableData.splice(index, 1);
      });
    },
    //弹窗更新完后端数据后，实时更新表格数据
    handleUpdate(roleObj) {
      console.log("子父通信", roleObj);
      this.drawer = false;
      let { tableData } = this;
      for (let i = 0; i < tableData.length; i++) {
        if (tableData[i].objectId == roleObj.objectId) {
          tableData[i] = roleObj; //修改本地
          return;
        }
      }
      tableData.push(roleObj); //本地新增
    },
  },
};
</script>
